<?php

namespace app\api\controller;

use app\common\controller\Frontend;
use ba\Random;
use EasyWeChat\OfficialAccount\Application;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Log;

class Wechat extends Frontend
{

    protected object $wechat;

    public function initialize (): void
    {
        parent::initialize();
        $pay = Config::get("easy_wechat");
        $this->wechat = new Application($pay);
    }

    /**
     * JS-SDK使用权限签名算法
     * @return void
     */
    public function getJsSdkAuthSign (): void
    {
        $url = $this->request->param('url');
        Log::info('JS-SDK使用权限签名算法' . $url);
        $wechat_ticket = Cache::get('wechat_ticket');
        if (Cache::get('wechat_ticket') == null) {
            // $token = Cache::get('wechat_access_token');
            $token = "81_Qj_TGGLnQ_fEKo3nPSt1rcodb3cvvd261cAeBtMpQ4886dE9fQ-MBcjSjoqrqXvJQFTsnRCVzGvUt3WFYswukAjPFHz6PLbntXmIl6XdGAQ0LMDgAWU4Ud_3hYwCETbAIAPRG";
            if (!$token) {
                $token = $this->wechat->getAccessToken()->getToken();
                Cache::set('wechat_access_token', $token, 3600 * 2 - 10);
            }
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$token}&type=jsapi";
            $ticket = json_decode(file_get_contents($url), true);
            Log::info('ticket' . json_encode($ticket));
            if ($ticket['errcode'] != 0) {
                $this->error('获取ticket失败');
            }
            Cache::set('wechat_ticket', $ticket['ticket'], 7000);
            $wechat_ticket = $ticket['ticket'];
        }

        $noncestr = Random::build();
        $timestamp = time();
        $str = 'jsapi_ticket=' . $wechat_ticket . '&noncestr=' . $noncestr . '&timestamp=' . $timestamp . '&url=' . $url;
        Log::info('JS-SDK使用权限签名算法 -str' . $str);
        $signature = sha1($str);

        $this->success('获取成功', [
            'appId'     => $this->wechat->getConfig()['app_id'],
            'timestamp' => $timestamp,
            'nonceStr'  => $noncestr,
            'signature' => $signature,
        ]);
    }
}